import base64, pickle
from django_redis import get_redis_connection


def marge_cart_cookie_to_redis(request, user, response):
    """把cookie购物车数据合并到redis"""
    # 获取cookie中的购物车数据
    cart_str = request.COOKIES.get('cart')
    if not cart_str:
        return response
    cookie_cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

    # 获取redis中的购物车数据
    redis_conn = get_redis_connection('cart')
    redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)
    # redis_selected_set = redis_conn.smembers('selected_%s' % user.id)
    # 定义一个字典变量用来合并购物车数据
    new_redis_cart_dict = {}
    # 先将redis中的数据装入字典中
    for sku_id_bytes, count_bytes in redis_cart_dict.items():
        new_redis_cart_dict[int(sku_id_bytes)] = int(count_bytes)
    # 遍历cookie购物车字典
    pl = redis_conn.pipeline()
    for sku_id, sku_dict in cookie_cart_dict.items():
        new_redis_cart_dict[sku_id] = sku_dict['count']
        # 将勾选的商品加入到redis的set中
        if sku_dict['selected']:
            # redis_selected_set.add(sku_id)
            pl.sadd('selected_%s' % user.id, str(sku_id).encode())

    # 把合并后的new_redis_cart_dict打字典中数据存储到redis中
    pl.hmset('cart_%s' % user.id, new_redis_cart_dict)
    # 执行
    pl.execute()

    # 把response中的购物车数据删除
    response.delete_cookie('cart')

    return response



